#ifndef  ECHO_H
#define  ECHO_H

#include  "fcgi_config.h"
#include  "fcgio.h"
#include  "fcgiapp.h"


#include  <sys/types.h>
#include  <unistd.h>
#include    <stdlib.h>
#include    <string>
#include    <sys/stat.h>
#include    <time.h>
#include    <fstream>
#include    <iostream>

using namespace std;

char **initialEnv = environ;

static const unsigned long STDIN_MAX = 1000000;

static void penv( const char *const *envp )
{
	cout << "<PRE>\n";
	for(; *envp; ++envp ) {
		cout << *envp << "\n";
	}
	cout << "</PRE>\n";
}

static long gstdin( FCGX_Request *request, char **content )
{
	char *clenstr = FCGX_GetParam( "CONTENT_LENGTH", request->envp );
	unsigned long clen = STDIN_MAX;

	if( clenstr ) {
		clen = strtol( clenstr, &clenstr, 10 );
		if( *clenstr ) {
			cerr << "can't parse \"CONTENT_LENGTH="
				 << FCGX_GetParam( "CONTENT_LENGTH", request->envp )
				 << "\"\n";
			clen = STDIN_MAX;
		}

		if( clen > STDIN_MAX ) clen = STDIN_MAX;

		*content = new char[clen];

		cin.read( *content, clen );
		clen = cin.gcount();
	}
	else {
		*content = 0;
		clen = 0;
	}

	do cin.ignore( 1024 ); while( cin.gcount() == 1024 );

	return clen;
}

static void echo( FCGX_Request &request )
{
	static int count = 0;
	long pid = getpid();

	char *content;
	unsigned long clen = gstdin( &request, &content );

	cout << "Content-type: text/html\r\n"
	"\r\n"
	"<TITLE>FakeUGC Echo</TITLE>\n"
	"<H1>FakeUGC Echo</H1>\n"
	"<H4>PID: " << pid << "</H4>\n"
	"<H4>Request Number: " << ++count << "</H4>\n";

	cout << "<H4>Request Environment</H4>\n";
	penv( request.envp );

	cout << "<H4>Process/Initial Environment</H4>\n";
	penv( environ );

	cout << "<H4>Standard Input - " << clen;
	if( clen == STDIN_MAX ) cout << " (STDIN_MAX)";
	cout << " bytes</H4>\n";
	if( clen ) cout.write( content, clen );

	if( content ) delete [] content;
}

#endif   // ----- #ifndef ECHO_H  -----
